<script setup lang="ts">
import { useEventListener } from '@peng_kai/kit/libs/vueuse';
import { ApiError } from '@peng_kai/kit/request';
import { openCurrencySelector } from '~/layouts/default/header/wallet/helpers';
import { useLocale } from '~/modules/locale';
import GameLoading from '~/pages/play/self/GameLoading.vue';
import { TEST_CURRENCY, useCurrencyStore } from '~/stores/currency';

const props = defineProps<{
  gameCode: string;
}>();

const isAuthed = useAuthed();
const $iframe = ref<HTMLIFrameElement>();
const loading = useBoolean(true);
const currencyStore = useCurrencyStore();
const appStore = useAppStore();
const { cryptoName: betCurrency } = storeToRefs(currencyStore);
const { locale } = useLocale();
const gameSrcQry = useQuery({
  gcTime: 0,
  enabled: isAuthed,
  queryKey: [apis.apiSportLaunchGame.id, toRef(props, 'gameCode'), betCurrency],
  queryFn: () => apis.apiSportLaunchGame(
    { game_code: props.gameCode, bet_currency: betCurrency.value! },
    { headers: import.meta.env.DEV ? { uid: '1' } : {} },
  ),
  retry(failureCount, error) {
    if (error instanceof ApiError && error.code === 11000) {
      return false;
    }
    return failureCount < 3;
  },
});
const appSocket = useAppSocket();
const gameSrcError = shallowRef<Error | null>(null);
const originUrl = ref('');

function updateUrlGame(originUrl: string) {
  if (!originUrl)
    return;

  const url = new URL(originUrl);

  url.searchParams.set('mode', 'DARK');

  {
    let localeCode = locale.value.toLowerCase();
    localeCode = localeCode === 'zh-hk' ? 'zh-tw' : localeCode;
    localeCode = localeCode.includes('zh-') ? localeCode : localeCode.split('-')[0];
    url.searchParams.set('locale', localeCode);
  }

  if ($iframe.value) {
    $iframe.value.src = url.toString();
  }
}

appSocket.receive('USER_ADD_BALANCE_RESP', 'AddBalanceResp', async (res) => {
  if (res.Data?.Type === 7 || res.Data?.Type === 8) {
    currencyStore.refetch();
  }
});

watch(gameSrcQry.data, (data) => {
  const iframeWin = $iframe.value?.contentWindow;

  if (!data || !iframeWin)
    return;

  if (data.type === 'url') {
    originUrl.value = data.data;
  }
});

watch(gameSrcQry.status, (status) => {
  if (status === 'pending') {
    loading.setTrue();
    gameSrcError.value = null;
  }

  if (status === 'error') {
    loading.setFalse();
    gameSrcError.value = gameSrcQry.error.value;
  }
}, { immediate: true });

watchEffect(() => {
  updateUrlGame(originUrl.value);
});

useEventListener('message', (ev) => {
  if (!Array.isArray(ev.data?.value?.data))
    return;

  const [type, data] = ev.data?.value?.data ?? [];

  if (type === 'set_application_state') {
    if (data.readyState === 'bootstrapped') {
      loading.setFalse();
    }
  }
});
</script>

<template>
  <div class="abs-full">
    <!-- 未登录 -->
    <div v-if="!isAuthed" class="abs-full flex-center">
      <I18nT keypath="ejifhh6PhQc0y3sihaBn3">
        <template #text>
          &nbsp;<span class="url-yellow-underline" @click="globalPopups.sign.open()">{{ $t('qwZi820O3qWpsae62Juc') }}</span>
        </template>
      </I18nT>
    </div>

    <!-- 已登录，但接口报错 -->
    <template v-else-if="gameSrcError">
      <div class="abs-full flex-center text-red-500">
        <!-- 不支持测试币 -->
        <div v-if="(gameSrcError instanceof ApiError && gameSrcError.code === 11000)" class="text-center">
          <div>{{ $t('yRs2TSbGkDq10wvgaY2m') }}</div>
          <div class="mt-2 url-yellow-underline" @click="openCurrencySelector">
            {{ $t('kfH6U72ViZgP8zd6SoKmx') }}
          </div>
        </div>

        <!-- 默认显示 -->
        <template v-else>
          {{ gameSrcError }}
        </template>
      </div>
    </template>

    <!-- 正常玩 -->
    <template v-else>
      <iframe ref="$iframe" class="block size-full border-none bg-sys-layer-c outline-none" :class="{ invisible: loading.is }" />
      <GameLoading v-if="loading.is" class="z-1" />
    </template>
  </div>
</template>
